import React from 'react';
import {StyleSheet, View} from 'react-native';
import Toast from 'react-native-easy-toast';

import api from '../../../common/api';

import Top from './top';
import Amount from './amount';
import Nav from './nav';
import Link from './link';
import auth from '../../../common/auth';

export default class extends React.Component {
    state = {
        isLogin: false,
        userInfo: {},
        present_month_price: 0,             //本月预估
        today_price: 0,                     //今日收益
        fans_number: 0,                     //粉丝数量
        can_withdraw_cash: 0                //可提现金额
    };

    //获取数据
    getData() {
        api({url: 'api/member/getUserMineIndexInfo'})
            .then(data => {
                const {present_month_price, today_price, fans_number, can_withdraw_cash} = data;
                this.setState({
                    present_month_price,
                    today_price,
                    fans_number,
                    can_withdraw_cash
                });
            })
            .catch(e => {
                console.log(e);
            });
    }

    //toast弹出
    showToast = (text, time = 1000) => {
        this.refs.toast.show(text, time);
    };

    componentDidMount() {
        this._didFocusSubscription = this.props.navigation.addListener(
            'didFocus',
            () => {
                auth.getUserInfo()
                    .then(userInfo => {
                        this.setState({
                            isLogin: true,
                            userInfo: userInfo
                        }, () => {
                            this.getData();
                        });
                    })
                    .catch(() => {
                        this.setState({
                            isLogin: false
                        });
                    });
            }
        );
    }

    componentWillUnmount() {
        this._didFocusSubscription && this._didFocusSubscription.remove();
    }

    render() {
        const {navigation} = this.props;
        const {present_month_price, today_price, fans_number, can_withdraw_cash, userInfo, isLogin} = this.state;
        return (
            <View style={styles.container}>
                <Top userInfo={userInfo} isLogin={isLogin} navigation={navigation}/>
                <Amount present_month_price={present_month_price}
                        today_price={today_price}
                        fans_number={fans_number}
                        can_withdraw_cash={can_withdraw_cash}
                        isLogin={isLogin}
                        navigation={navigation}/>
                <Nav navigation={navigation} isLogin={isLogin}/>
                <Link navigation={navigation}/>
                <Toast ref="toast" position="center"/>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        backgroundColor: '#f0f0f0',
        flex: 1
    }
});
